﻿using Biz.Buffer;
using Biz.EF.Platform.SG;
using Biz.Process.Entity;
using Hjt212Parser;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Biz.Process
{
    public static class Processor2051
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(Processor2051));
        private static readonly List<string> ExistTable = new List<string>();
        public static void Process(string content)
        {
            Log.Info("Processor2051 begins processing.");
            string sql = "";
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrWhiteSpace(mn)) return;
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue) return;
                var port = CommonInformation.GetLetportByMn(mn);
                if (port == null) return;
                var ecode = CommonInformation.GetPollutionSourceCodeByMn(mn);
                if (string.IsNullOrWhiteSpace(ecode)) return;

                using (var pCtx = new PlatformXpfContext())
                {
                    var tableName = "主分钟数据_企业ID".Replace("_企业ID", "_" + ecode);
                    int? count;
                    if (!ExistTable.Contains(tableName))
                    {
                        count = pCtx.Database.SqlQuery<int?>(Cmd2051Sqls.M_EXIST.Replace("_企业ID", "_" + ecode)).FirstOrDefault();
                        if (!count.HasValue || count < 1)
                        {
                            pCtx.Database.ExecuteSqlCommand(Cmd2051Sqls.M_CREATE.Replace("_企业ID", "_" + ecode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2051Sqls.M_ALTER_1.Replace("_企业ID", "_" + ecode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2051Sqls.M_ALTER_2.Replace("_企业ID", "_" + ecode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2051Sqls.M_NONCLUSTERED_1.Replace("_企业ID", "_" + ecode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2051Sqls.M_NONCLUSTERED_2.Replace("_企业ID", "_" + ecode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2051Sqls.M_NONCLUSTERED_3.Replace("_企业ID", "_" + ecode));
                        }
                        ExistTable.Add(tableName);
                    }
                    var codes = Parser.GetPollutantCodes(content);
                    if (codes == null) return;
                    Master master = new Master();

                    master.enterpriseId = port.企业基本信息ID;
                    master.letportId = port.ID;
                    DateTime time = datatime.Value;
                    master.monitorTime = time;
                    //todo:主污染物可以在此增加
                    if (codes.Contains("B01") || codes.Contains("w00000"))
                    {
                        master.contamTypeId = 2;
                        var rtd = Parser.GetDoubleByKey("B01-Cou", content);
                        if (codes.Contains("w00000")) rtd=Parser.GetDoubleByKey("w00000-Cou", content);
                        master.sum = rtd ?? 0;
                    }
                    else if (codes.Contains("B02") || codes.Contains("a00000"))
                    {
                        master.contamTypeId = 1;
                        var rtd = Parser.GetDoubleByKey("B02-Cou", content);
                        if (codes.Contains("a00000")) rtd=Parser.GetDoubleByKey("a00000-Cou", content);
                        master.sum = rtd ?? 0;
                    }
                    master.rtd = 0;
                    var begin = new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute / 5 * 5, 0);
                    var end = begin.AddMinutes(5);
                    //todo:(1 == 2)可以灵活更改
                    var whereCause =
                        (1 == 2)
                        ?
                        "企业排口ID=" + port.ID + " and 监测时间>='" + begin.ToString("yyyy-MM-dd HH:mm:ss") + "' and 监测时间<'" + end.ToString("yyyy-MM-dd HH:mm:ss") + "'"
                        :
                        "企业排口ID=" + port.ID + " and 监测时间='" + time.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                    sql = Cmd2051Sqls.M_SELECT.Replace("_企业ID", "_" + ecode).Replace("{搜索条件}", whereCause);


                    count = pCtx.Database.SqlQuery<int?>(sql).FirstOrDefault();

                    if (!count.HasValue || count < 1)
                    {
                        sql = Cmd2051Sqls.M_INSERT
                              .Replace("_企业ID", "_" + ecode)
                              .Replace("{企业排口ID}", "" + master.letportId)
                              .Replace("{监测时间}", "'" + master.monitorTime.ToString("yyyy-MM-dd HH:mm:ss") + "'")
                              .Replace("{污染物类别ID}", "" + master.contamTypeId)
                              .Replace("{时段量}", "" + master.sum);

                        pCtx.Database.ExecuteSqlCommand(sql);
                    }
                    else
                    {
                        sql = Cmd2051Sqls.M_UPDATE
                            .Replace("_企业ID", "_" + ecode)
                            .Replace("{企业排口ID}", "" + master.letportId)
                            .Replace("{监测时间}", "'" + master.monitorTime.ToString("yyyy-MM-dd HH:mm:ss") + "'")
                            .Replace("{污染物类别ID}", "" + master.contamTypeId)
                            .Replace("{时段量}", "" + master.sum)
                            .Replace("{搜索条件}", whereCause);

                        pCtx.Database.ExecuteSqlCommand(sql);
                    }
                    sql = Cmd2051Sqls.M_SELECT.Replace("_企业ID", "_" + ecode).Replace("{搜索条件}", whereCause).Replace("COUNT(1)", "ID");

                    var masterId = pCtx.Database.SqlQuery<int?>(sql).FirstOrDefault();
                    if (!masterId.HasValue) return;

                    Helper.RemoveMasterFactor(codes, true);

                    tableName = "从分钟数据_企业ID".Replace("_企业ID", "_" + ecode);
                    if (!ExistTable.Contains(tableName))
                    {
                        count = pCtx.Database.SqlQuery<int?>(Cmd2051Sqls.D_EXIST.Replace("_企业ID", "_" + ecode)).FirstOrDefault();
                        if (!count.HasValue || count < 1)
                        {
                            pCtx.Database.ExecuteSqlCommand(Cmd2051Sqls.D_CREATE.Replace("_企业ID", "_" + ecode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2051Sqls.D_ALTER_1.Replace("_企业ID", "_" + ecode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2051Sqls.D_ALTER_2.Replace("_企业ID", "_" + ecode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2051Sqls.D_NONCLUSTERED_1.Replace("_企业ID", "_" + ecode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2051Sqls.D_NONCLUSTERED_2.Replace("_企业ID", "_" + ecode));
                        }
                        ExistTable.Add(tableName);
                    }
                    Slave slave = new Slave();
                    slave.masterId = masterId.Value;

                    foreach (var code in codes)
                    {
                        var contam = CommonInformation.GetContamCode(code);
                        if (contam == null) continue;
                        slave.contamId = contam.ID;
                        var cou = Parser.GetDoubleByKey(code + "-Cou", content);
                        slave.cou = cou.HasValue ? cou.Value : 0;
                        slave.zsCou = Parser.GetDoubleByKey(code + "-ZsCou", content);
                        slave.min = Parser.GetDoubleByKey(code + "-Min", content);
                        slave.zsMin = Parser.GetDoubleByKey(code + "-ZsMin", content);
                        slave.avg = Parser.GetDoubleByKey(code + "-Avg", content);
                        slave.zsAvg = Parser.GetDoubleByKey(code + "-ZsAvg", content);
                        slave.max = Parser.GetDoubleByKey(code + "-Max", content);
                        slave.zsMax = Parser.GetDoubleByKey(code + "-ZsMax", content);
                        whereCause = "主分钟数据ID=" + slave.masterId + " and 污染物编码ID=" + slave.contamId;
                        sql = Cmd2051Sqls.D_SELECT.Replace("_企业ID", "_" + ecode).Replace("{搜索条件}", whereCause);

                        count = pCtx.Database.SqlQuery<int?>(sql).FirstOrDefault();
                        if (!count.HasValue || count < 1)
                        {
                            sql = Cmd2051Sqls.D_INSERT
                                  .Replace("_企业ID", "_" + ecode)
                                  .Replace("{主分钟数据ID}", "" + slave.masterId)
                                  .Replace("{污染物编码ID}", "" + slave.contamId)
                                  .Replace("{Cou}", "" + slave.cou)
                                  .Replace("{ZSCou}", slave.zsCou.HasValue ? "" + slave.zsCou : "null")
                                  .Replace("{Min}", slave.min.HasValue ? "" + slave.min : "null")
                                  .Replace("{ZSMin}", slave.zsMin.HasValue ? "" + slave.zsMin : "null")
                                  .Replace("{Avg}", slave.avg.HasValue ? "" + slave.avg : "null")
                                  .Replace("{ZSAvg}", slave.zsAvg.HasValue ? "" + slave.zsAvg : "null")
                                  .Replace("{Max}", slave.max.HasValue ? "" + slave.max : "null")
                                  .Replace("{ZSMax}", slave.zsMax.HasValue ? "" + slave.zsMax : "null");

                            pCtx.Database.ExecuteSqlCommand(sql);
                        }
                        else
                        {
                            sql = Cmd2051Sqls.D_UPDATE
                                .Replace("_企业ID", "_" + ecode)
                                .Replace("{主分钟数据ID}", "" + slave.masterId)
                                .Replace("{污染物编码ID}", "" + slave.contamId)
                                .Replace("{Cou}", "" + slave.cou)
                                .Replace("{ZSCou}", slave.zsCou.HasValue ? "" + slave.zsCou : "null")
                                .Replace("{Min}", slave.min.HasValue ? "" + slave.min : "null")
                                .Replace("{ZSMin}", slave.zsMin.HasValue ? "" + slave.zsMin : "null")
                                .Replace("{Avg}", slave.avg.HasValue ? "" + slave.avg : "null")
                                .Replace("{ZSAvg}", slave.zsAvg.HasValue ? "" + slave.zsAvg : "null")
                                .Replace("{Max}", slave.max.HasValue ? "" + slave.max : "null")
                                .Replace("{ZSMax}", slave.zsMax.HasValue ? "" + slave.zsMax : "null")
                                .Replace("{搜索条件}", whereCause);

                            pCtx.Database.ExecuteSqlCommand(sql);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(sql);
                Log.Error(ex);
                Log.Error(content);
            }

            Log.Info("Processor2051 ends processing.");
        }
    }
}
